//
//  UIContactsViewController.m
//  TTAddressBook
//
//  Created by wangming on 11-12-28.
//  Copyright (c) 2011年 __MyCompanyName__. All rights reserved.
//

#import "UIContactsViewController.h"
#import <QuartzCore/QuartzCore.h>
#import "define.h"
#import "define.h"
#import "UIPopView.h"
#import "selectContactViewController.h"
#import "UICustomNavigationBar.h"
#import "UIGroupViewController.h"



@implementation UIContactsViewController


@synthesize ContactsList,timeObjectArr,tableview,LefttableView,groupNames,Cur_ContactID,Cur_ContactName,filteredListContent,Cur_GroupID,Cur_GroupName,Cur_GroupType;
@synthesize selectedRowIndex;
@synthesize lastSelectedRowIndex;
@synthesize opened;
@synthesize personImageDict;
@synthesize strShowName;


-(void) ChooseContact{
    selectContacts* view = [[selectContacts alloc] initWithContacts:ContactsList];
    [self.navigationController pushViewController:view animated:YES];
    [view release];
}

- (void) showGroupTable{
    if (ShowGroup_Flag){
        ShowGroup_Flag = NO;//显示左边栏
        selSearchBar.frame     = CGRectMake(0, 0, 240, 44);
        segCon.frame = CGRectMake(10, 45, 220, 30);
        tableview.frame     = CGRectMake(80, 0, 240, tableview.frame.size.height);        
        LefttableView.frame = CGRectMake(0, 0, 80, 366);  
        if(ContactsList)
            [tableview reloadData];
    }
    else{
        ShowGroup_Flag = YES;//不显示左边栏    
        selSearchBar.frame     = CGRectMake(0, 0, 320, 44);
        segCon.frame = CGRectMake(10, 45, 300, 30);
        tableview.frame     = CGRectMake(0, 0, 320, tableview.frame.size.height);
        selSearchBar.frame     = CGRectMake(0, 0, 320, 44);
        LefttableView.frame = CGRectMake(0, 0, 0, 366);
        if(ContactsList)
            [tableview reloadData];
    }
}

- (void) showContactsGroup
{   
    
    [self showGroupTable];	
}
-(void)getgroups{
    NSDictionary * retgroup = [[MyClass getInstance] listGroup];
    if ([[retgroup objectForKey:@"code"] intValue]==0) {
        NSArray * arr = [retgroup objectForKey:@"list"];
        if (self.groupNames) {
            [self.groupNames removeAllObjects]; 
        }
        else
            self.groupNames = [[NSMutableArray alloc] init];
        [self.groupNames addObjectsFromArray:arr];
    }
}  
-(void)getContacts:(NSInteger)type{   
    NSString* groupname=nil;
    NSString* grouptype=nil;
    if (Cur_GroupID>0) 
    if ([Cur_GroupName length]>0) {
        groupname = self.Cur_GroupName;
    }
    if ([Cur_GroupType length]>0) {
        grouptype = self.Cur_GroupType;
    }
    if (type==1) 
        startAt=0;
    NSDictionary * ret = [[MyClass getInstance] getMembers: groupname ofType:grouptype inOrder:inOrder startAt:startAt limit:15 searchWith:nil];
    if ([[ret objectForKey:@"total"] intValue] > 0) {
        NSArray * arr = [ret objectForKey:@"list"];
        if (self.ContactsList) {
            if (type==1){
                [self.ContactsList removeAllObjects]; 
                startAt=[arr count];
            }
            else
                 startAt+=[arr count];
        }
        else{
            self.ContactsList = [[NSMutableArray alloc] init];
            startAt=[arr count];
        }
        [self.ContactsList addObjectsFromArray:arr];
    }
}
-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    if (scrollView.contentOffset.y+scrollView.frame.size.height-40 > scrollView.contentSize.height) {
        [self getContacts:2];
        [tableview reloadData];
    }
   // NSLog(@"x is %f y is %f , height is %f",scrollView.contentOffset.x,scrollView.contentOffset.y,scrollView.frame.size.height);
}
- (void)viewDidLoad {
    [[selSearchBar.subviews objectAtIndex:0]removeFromSuperview];
    tableview.delegate=self;
	tableview.dataSource=self;
    tableview.tag = UIContactsViewController_ContactsTableView;
    LefttableView.delegate=self;
	LefttableView.dataSource=self;
	LefttableView.backgroundColor=[UIColor clearColor];
    LefttableView.tag = UIContactsViewController_GroupTableView;
    ShowGroup_Flag = NO;
    Cur_ContactID = -1;
    startAt=0;
    inOrder=2;
    selectedRowIndex = lastSelectedRowIndex = -1;
    opened= NO;
    [self showGroupTable];
    
    UIBarButtonItem *ButtonItemGropu =[[UIBarButtonItem alloc] initWithTitle:@"分组" style:(UIBarButtonItemStyleBordered)  target:self action:@selector(showContactsGroup)];
    ButtonItemGropu.width = 50;
    
    self.navigationItem.leftBarButtonItem = ButtonItemGropu;
    [ButtonItemGropu release];
	
    UIBarButtonItem *ButtonItemAction = [[UIBarButtonItem alloc] initWithTitle:@"选择" style:(UIBarButtonItemStyleBordered) target:self action:@selector(ChooseContact)];
    self.navigationItem.rightBarButtonItem = ButtonItemAction;
    [ButtonItemAction release];
    self.title = @"社区";
	selSearchBar = [[[UISearchBar alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, 44.0f)] autorelease];
	selSearchBar.autocorrectionType = UITextAutocorrectionTypeNo;
	selSearchBar.autocapitalizationType = UITextAutocapitalizationTypeNone;
    selSearchBar.delegate = self;
    headerView=[[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 88)];
    [headerView addSubview:selSearchBar];
    [selSearchBar release];
    segCon = [[[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:@"√ 时间排序", @"名称排序", nil]] autorelease];
	[segCon addTarget:self action:@selector(segmentChangedValue:) forControlEvents:UIControlEventValueChanged];
    segCon.selectedSegmentIndex=0;
    segCon.frame = CGRectMake(10, 45, 300, 30);  
    segCon.segmentedControlStyle= UISegmentedControlStyleBar;
    segCon.tintColor=[UIColor colorWithRed:190.0/255 green:0.0 blue:30.0/255 alpha:1.0];
    [headerView addSubview:segCon];  
	tableview.tableHeaderView = headerView;

	searchDC = [[UISearchDisplayController alloc] initWithSearchBar:selSearchBar contentsController:self];
	searchDC.searchResultsDataSource = self;
	searchDC.searchResultsDelegate = self;
    searchDC.delegate = self;
    selSearchBar.backgroundColor = [UIColor colorWithRed:214.0/255 green:217.0/255 blue:222.0/255 alpha:1.0];
    [[selSearchBar.subviews objectAtIndex:0] removeFromSuperview];
    [self getgroups];
    [self getContacts:1];
    self.personImageDict = [[NSMutableDictionary alloc] init];
}
- (void)segmentChangedValue:(id)sender {
   // NSLog(@"%d",[(UISegmentedControl *)sender selectedSegmentIndex]);
    switch([(UISegmentedControl *)sender selectedSegmentIndex])
    {
        case 0:
            inOrder=2;
            [self getContacts:1];
            selectedRowIndex = lastSelectedRowIndex = -1;
            opened= NO;
            [segCon setTitle:@"√ 时间排序" forSegmentAtIndex:0];
            [segCon setTitle:@"名称排序" forSegmentAtIndex:1];
            [tableview reloadData];
            break;             
        case 1: 
            inOrder=1;
            [self getContacts:1];
            selectedRowIndex = lastSelectedRowIndex = -1;
            opened= NO;
            [segCon setTitle:@"时间排序" forSegmentAtIndex:0];
            [segCon setTitle:@"√ 名称排序" forSegmentAtIndex:1];
            [tableview reloadData];
            break;                        
        default:             
            break;
    }

}


-(void) viewDidAppear:(BOOL)animated{
    if (ContactsList)
    for (NSMutableDictionary * dict  in self.ContactsList) {
        ([dict setObject:@"false" forKey:@"check"]);
    }

}
-(void) viewWillDisappear:(BOOL)animated{
   self.personImageDict=nil;
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    double height; 
    height = 44;
    NSInteger row = indexPath.row;
    if (tableView.tag!= UIContactsViewController_GroupTableView)
    if ( opened && row == selectedRowIndex)
    {
        return height+30;
    }
    return height;
}

- (void)viewDidUnload {
    self.ContactsList = nil;
    self.timeObjectArr = nil;
    self.groupNames=nil;
}
- (void)dealloc {
    for(UIView* u in self.view.subviews){
        if (u.tag == MENUVIEW_TAG) {
            [u removeFromSuperview];
        }
    }
    [filteredListContent removeAllObjects];
    self.filteredListContent = nil;
    [segCon release];
    segCon=nil;
    [selSearchBar release];
    selSearchBar=nil;
    [headerView release];
    headerView=nil;
    [searchDC release];
    [ContactsList release];
    [timeObjectArr release];
    groupNames =nil;
    self.personImageDict=nil;
    self.strShowName=nil;
    [super dealloc];
}

- (void) btnTimeObj:(id)sender{
    UIShowTimeObjListViewController* view = [[UIShowTimeObjListViewController alloc] initWithTimeObjList:self.timeObjectArr showname:strShowName];
    [self.navigationController pushViewController:view animated:YES];
    [view release];
}
- (void) btnSendSms:(id)sender{
    UITableViewCell * cell= ((UITableViewCell*)[sender superview]);
    NSInteger row =[tableview indexPathForCell:cell].row;
    NSMutableArray * array=[[NSMutableArray alloc] init];
    [array addObject:[ContactsList objectAtIndex:row]];
    if ([MyClass getInstance].personMarkList) {
        [[MyClass getInstance].personMarkList removeAllObjects];
    }
    else
    {
        [MyClass getInstance].personMarkList = [[NSMutableArray alloc] init];
    }
    [[MyClass getInstance].personMarkList addObject:[ContactsList objectAtIndex:row]];
    composeMessageViewController *view = [[composeMessageViewController alloc] initWithContact:array];
    [self.navigationController pushViewController:view animated:YES];
    [view release];
    [array release];
}
- (void) btnShowSms:(id)sender{
    UITableViewCell * cell= ((UITableViewCell*)[sender superview]);
    NSInteger row =[tableview indexPathForCell:cell].row;
    NSDictionary *dict = [ContactsList objectAtIndex:row];
    detailMessageViewController *view = [[detailMessageViewController alloc] initWithOneContact:dict];
    [self.navigationController pushViewController:view animated:YES];
    [view release];
}

#pragma mark -
#pragma mark Table View Data Source Methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView 
 numberOfRowsInSection:(NSInteger)section
{   //需要设置分组的话，可以再加1
    if(tableView.tag==UIContactsViewController_GroupTableView) return [groupNames count]+1;
    if(tableView.tag==UIContactsViewController_ContactsTableView) {
        return [ContactsList count];
    }
    return [self.filteredListContent count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView 
         cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSUInteger row = [indexPath row];
    UITableViewCell *cell;
    if (tableView.tag==UIContactsViewController_GroupTableView) {
         static NSString *SectionsTableIdentifier = @"LeftTableIdentifier";
        cell = [tableview dequeueReusableCellWithIdentifier:
                SectionsTableIdentifier ];
        if (cell == nil) {
            cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle 
                                           reuseIdentifier: SectionsTableIdentifier ] autorelease];
            cell.accessoryType = UITableViewCellAccessoryNone;
            [cell setBackgroundView:[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"contacts_group.png"]]];
            [cell setSelectedBackgroundView:[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"contacts_group_on.png"]]];
        }
        [cell textLabel].font =  [UIFont systemFontOfSize:12];
       if (row==0) {
           [cell textLabel].text =@"全部";
            [cell textLabel].font =  [UIFont systemFontOfSize:14];
       }else if (row < [groupNames count]+1){
           NSDictionary* dict=[groupNames objectAtIndex:row-1];
           //int type 组类型，1-客户，2-团队，3-社区
           [cell textLabel].text = [dict objectForKey:@"name"];
           NSString* strType;
           switch ([[dict objectForKey:@"type"] intValue]) {
               case 1:
                   strType=@"客户";
                   break;
               case 2:
                   strType=@"团队";
                   break;
               case 3:
                   strType=@"社区";
                   break;
               default:
                   break;
           }
           [cell detailTextLabel].font =  [UIFont systemFontOfSize:12];
           [cell detailTextLabel].text = strType; 
       }
       else
           [cell textLabel].text = @"设置";
       
    }
    else{        
        static NSString *SectionsTableIdentifier = @"SectionsTableIdentifier";
        
        cell = [tableView dequeueReusableCellWithIdentifier:
                SectionsTableIdentifier ];
        if (cell == nil) {
            cell = [[[UITableViewCell alloc] initWithStyle: UITableViewCellStyleDefault 
                                           reuseIdentifier: SectionsTableIdentifier ] autorelease];
            cell.accessoryType = UITableViewCellAccessoryNone;
            //cell.showsReorderControl=YES;
        }
        for (UIView *subview in cell.subviews) {
            if (subview.tag == 1001)              
            [subview removeFromSuperview];
        }
        NSDictionary *dict;
        //显示联系人，头像等信息。
        if (tableView.tag== UIContactsViewController_ContactsTableView)
        {
            dict = [self.ContactsList objectAtIndex:row];
            //infoItem = [nameSection objectAtIndex:row];    
            UILabel* lab1; 
            lab1 = [[UILabel alloc] init];
            lab1.frame = CGRectMake(65, 5, 160, 22);
            lab1.text = [dict objectForKey:@"personShowName"];
            lab1.font = [UIFont boldSystemFontOfSize:19];
            lab1.backgroundColor = [UIColor clearColor];           
            lab1.tag = 1001;
            [cell addSubview:lab1];
            [lab1 release]; 
            if (opened && row == selectedRowIndex) {
                UIButton * btnTimeObj;
                btnTimeObj=[UIButton buttonWithType:UIButtonTypeRoundedRect];
                btnTimeObj.frame=CGRectMake(15, 46, 90, 26);
                btnTimeObj.tag=1001;
                [btnTimeObj addTarget:self action:@selector(btnTimeObj:) forControlEvents:UIControlEventTouchUpInside];
                [cell addSubview:btnTimeObj];
                //[btnTimeObj release];
                
//                UIButton * btnSendSms;
//                btnSendSms=[UIButton buttonWithType:UIButtonTypeRoundedRect];
//                btnSendSms.frame=CGRectMake(115, 46, 90, 26);
//                btnSendSms.tag=1001;
//                [btnSendSms setTitle:@"发送消息" forState:(UIControlStateNormal)];
//                [btnSendSms addTarget:self action:@selector(btnSendSms:) forControlEvents:UIControlEventTouchUpInside];
//                [cell addSubview:btnSendSms];
//               // [btnSendSms release];
                
                UIButton * btnShowSms;
                btnShowSms=[UIButton buttonWithType:UIButtonTypeRoundedRect];
                btnShowSms.frame=CGRectMake(115, 46, 90, 26);
                btnShowSms.tag=1001;
                [btnShowSms setTitle:@"消息" forState:(UIControlStateNormal)];
                [btnShowSms addTarget:self action:@selector(btnShowSms:) forControlEvents:UIControlEventTouchUpInside];
                [cell addSubview:btnShowSms];
                
                if (!ShowGroup_Flag) {
                    btnTimeObj.frame=CGRectMake(15, 46, 65, 26); 
                    //btnSendSms.frame=CGRectMake(115-25, 46, 65, 26);
                    btnShowSms.frame=CGRectMake(115-25, 46, 65, 26);
                }
                
                
                //[btnShowSms release];
                NSDictionary *dict = [self.ContactsList objectAtIndex:indexPath.row];
                NSString * strMark = [dict objectForKey:@"personMark"];  
                 NSString * str = [dict objectForKey:@"personShowName"];  
                NSLog(@"%@",str);
                self.strShowName = str;
                NSDictionary * ret = [[MyClass getInstance] getSchedule:strMark];
                if ([[ret objectForKey:@"code"] intValue]==0) {
                    if ([ret objectForKey:@"size"] > 0) 
                    {
                        if (timeObjectArr)
                            [timeObjectArr removeAllObjects];
                        else
                            timeObjectArr = [[NSMutableArray alloc] init];
                        
                        [timeObjectArr addObjectsFromArray:[ret objectForKey:@"list"]];
                    }
                    else {
                        if (timeObjectArr)
                            [timeObjectArr removeAllObjects];
                        else
                            timeObjectArr = [[NSMutableArray alloc] init];
                    }
                }  
                if ([timeObjectArr count]>0) {
                    NSString* str;                  
                    str=[NSString stringWithFormat:@"日程(%d)" ,[timeObjectArr count]];
                    [btnTimeObj setTitle:str forState:(UIControlStateNormal)];
                    btnTimeObj.titleLabel.textColor = [UIColor redColor];
                    [btnTimeObj setEnabled:YES];
                }
                else{
                    [btnTimeObj setTitle:[NSString stringWithFormat:@"日程(%d)" ,0] forState:(UIControlStateNormal)];
                    [btnTimeObj setEnabled:NO];
                }
                if (cell.frame.origin.y+cell.frame.size.height -tableView.contentOffset.y > tableView.frame.size.height){
                    NSInteger num = cell.frame.origin.y+cell.frame.size.height - tableView.contentOffset.y-tableView.frame.size.height;
                    CGPoint pt = CGPointMake(tableView.contentOffset.x, tableView.contentOffset.y+num);
                    tableView.contentOffset = pt;
                }
            }
        }
        else{//搜索结果
            //infoItem = [self.filteredListContent objectAtIndex:indexPath.row];
            dict = [self.filteredListContent objectAtIndex:row];
            [cell textLabel].textColor = [UIColor clearColor];
            UILabel* lab; 
            lab = [[UILabel alloc] initWithFrame:CGRectMake(65, 13, 160, 22)];
            lab.tag = 1001;
            lab.text = [dict objectForKey:@"personShowName"];
            lab.font = [UIFont boldSystemFontOfSize:19];
            lab.backgroundColor = [UIColor clearColor];           
            [cell addSubview:lab];
            [lab release];
            
            if (opened && row == selectedRowIndex) {
                UIButton * btnTimeObj;
                btnTimeObj=[UIButton buttonWithType:UIButtonTypeRoundedRect];
                btnTimeObj.frame=CGRectMake(15, 46, 90, 26);
                btnTimeObj.tag=1001;
                [btnTimeObj addTarget:self action:@selector(btnTimeObj:) forControlEvents:UIControlEventTouchUpInside];
                [cell addSubview:btnTimeObj];
                //[btnTimeObj release];
                
                UIButton * btnSendSms;
                btnSendSms=[UIButton buttonWithType:UIButtonTypeRoundedRect];
                btnSendSms.frame=CGRectMake(115, 46, 90, 26);
                btnSendSms.tag=1001;
                [btnSendSms setTitle:@"发送消息" forState:(UIControlStateNormal)];
                [btnSendSms addTarget:self action:@selector(btnSendSms:) forControlEvents:UIControlEventTouchUpInside];
                [cell addSubview:btnSendSms];
                // [btnSendSms release];
                
                UIButton * btnShowSms;
                btnShowSms=[UIButton buttonWithType:UIButtonTypeRoundedRect];
                btnShowSms.frame=CGRectMake(215, 46, 90, 26);
                btnShowSms.tag=1001;
                [btnShowSms setTitle:@"往来消息" forState:(UIControlStateNormal)];
                [btnShowSms addTarget:self action:@selector(btnShowSms:) forControlEvents:UIControlEventTouchUpInside];
                [cell addSubview:btnShowSms];
                //[btnShowSms release];
                NSDictionary *dict = [self.filteredListContent objectAtIndex:indexPath.row];
                NSString * strMark = [dict objectForKey:@"personMark"];                
                NSDictionary * ret = [[MyClass getInstance] getSchedule:strMark];
                if ([[ret objectForKey:@"code"] intValue]==0) {
                    if ([ret objectForKey:@"size"] > 0) {
                        if (timeObjectArr)
                            [timeObjectArr removeAllObjects];
                        else
                            timeObjectArr = [[NSMutableArray alloc] init];
                        
                        [timeObjectArr addObjectsFromArray:[ret objectForKey:@"list"]];
                    }
                }  
                if ([timeObjectArr count]>0) {
                    NSString* str;                  
                    str=[NSString stringWithFormat:@"日程(%d)" ,[timeObjectArr count]];
                    [btnTimeObj setTitle:str forState:(UIControlStateNormal)];
                    btnTimeObj.titleLabel.textColor = [UIColor redColor];
                    [btnTimeObj setEnabled:YES];
                }
                else{
                    [btnTimeObj setTitle:[NSString stringWithFormat:@"日程(%d)" ,0] forState:(UIControlStateNormal)];
                    [btnTimeObj setEnabled:NO];
                }
                if (cell.frame.origin.y > 480-44*3-30){
                    CGPoint pt = CGPointMake(tableView.contentOffset.x, tableView.contentOffset.y+40);
                    tableView.contentOffset = pt;
                }
                
            }

        }         
    
        UIImageView* imgview=[[UIImageView alloc] initWithFrame:CGRectMake(15, 5, 34, 34)];
        imgview.tag=1001;
        extern BOOL showPersonImage;
        if (showPersonImage)
        {          
            if (!personImageDict) 
                self.personImageDict = [[NSMutableDictionary alloc] init];
            if(![personImageDict objectForKey:[dict objectForKey:@"personMark"]])
            {
                NSDictionary * ret = [[MyClass getInstance] getPersonImage:[NSArray arrayWithObject:[dict objectForKey:@"personMark"]]];
                if ([[ret objectForKey:@"code"] intValue] == 0) {
                    NSData *imgData;
                    NSString* strMark = [dict objectForKey:@"personMark"];
                    imgData = [ret objectForKey:strMark];
                    UIImage * image;
                    image = [[UIImage alloc] initWithData:imgData];
                    if (image)
                        [personImageDict setObject:image forKey:[dict objectForKey:@"personMark"]];
                    else
                        [personImageDict setObject:[UIImage imageNamed:UIContacts_Contacts_icon] forKey:[dict objectForKey:@"personMark"]]; 
//                    [imgData release];
                    [image release];
                }
                else
                    imgview.image = [UIImage imageNamed:UIContacts_Contacts_icon]; 
            }
            imgview.image = [personImageDict objectForKey:[dict objectForKey:@"personMark"]];
        }
        else
            imgview.image = [UIImage imageNamed:UIContacts_Contacts_icon];  
        [cell addSubview:imgview];
    } 
    return cell;
}

- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView.tag == UIContactsViewController_GroupTableView){
        if (indexPath.row == [groupNames count]+1){
            Cur_GroupID = -2;
            [self reloadTableView];
            return  nil;
        }
    }
    return indexPath;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView.tag == UIContactsViewController_GroupTableView){
        NSInteger groupCount = [groupNames count];
        if (indexPath.row == 0) {
            self.Cur_GroupID = -1;
            self.Cur_GroupName = @"全部";
            self.Cur_GroupType = nil;
            self.title = @"全部";
            self.tabBarItem.title= @"社区";
        }
        else if (indexPath.row == groupCount+1) {
            self.Cur_GroupID = -2; 
            Cur_GroupName = @"设置";
            Cur_GroupType = nil;
        }
        else {
            self.Cur_GroupID  = indexPath.row;
            NSDictionary* dict = [groupNames objectAtIndex:indexPath.row-1];
            self.Cur_GroupName = [dict objectForKey:@"name"];
            self.Cur_GroupType = [dict objectForKey:@"type"];
            self.title = self.Cur_GroupName;
            self.tabBarItem.title = @"社区";
        }
        if (self.Cur_ContactID>-2) {
            [self getContacts:1];
            selectedRowIndex = lastSelectedRowIndex = -1;//合住cell
            opened= NO;
            [tableview reloadData];   
        }
    }
    else //if (tableView.tag== UIContactsViewController_ContactsTableView)
    {
        lastSelectedRowIndex = selectedRowIndex;
        selectedRowIndex = indexPath.row; 
        if ( self.opened && lastSelectedRowIndex != selectedRowIndex ){  //证明点击了新的一行
            [tableView reloadData]; 
            return;           
        }
        opened = !opened;
        if (opened) {
          
        }
        if (!opened)
        {
            selectedRowIndex = -1;
        }
        [tableView reloadData];
    }
}
-(void)reloadTableView{
    [tableview reloadData];
    [LefttableView reloadData];
}
- (void)filterContentForSearchText:(NSString*)searchText
{
	/*
	 Update the filtered array based on the search text and scope.
	 */
    if (filteredListContent) {
        [filteredListContent removeAllObjects]; // First clear the filtered array.
    }
    else
        filteredListContent = [[NSMutableArray alloc]init];
    if ([searchText length] == 0) {
        self.filteredListContent = nil;
    }
    else
    {//需要根据用户需求调整，如果用户需要加上拖动到头更新，那就要修改startat和limit，如果需要外层的分组限制搜索结果，那就要放开下面的代码
//        NSString* groupname=nil;
//        NSString* grouptype=nil;
//        if (Cur_GroupID>0) 
//            if ([Cur_GroupName length]>0) {
//                groupname = self.Cur_GroupName;
//            }
//        if ([Cur_GroupType length]>0) {
//            grouptype = self.Cur_GroupType;
//        }
        opened = NO;
        selectedRowIndex = -1;
        [tableview reloadData];
        NSDictionary * ret = [[MyClass getInstance] getMembers: nil ofType:nil inOrder:1 startAt:0 limit:300 searchWith:searchText];
        if ([[ret objectForKey:@"total"] intValue] > 0) {
            NSArray * arr = [ret objectForKey:@"list"];
            if (self.filteredListContent) {
//                if (type==1){
                    [self.filteredListContent removeAllObjects]; 
                    //startAt=[arr count];
//                }
//                else
//                    startAt+=[arr count];
            }
            else{
                self.filteredListContent = [[NSMutableArray alloc] init];
                //startAt=[arr count];
            }
            [self.filteredListContent addObjectsFromArray:arr];
        }
//        self.filteredListContent = 搜索返回结果;  
    }
}


#pragma mark -
#pragma mark UISearchDisplayController Delegate Methods

- (BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
    [self filterContentForSearchText:searchString];
    
    // Return YES to cause the search result table view to be reloaded.
    return YES;
}

#pragma mark -
#pragma mark UISearchBarDelegate Delegate Methods

- (void)searchBarCancelButtonClicked:(UISearchBar *) searchBar{
    
}

- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar
{   [searchBar setKeyboardType:6];
    [searchBar setShowsCancelButton:YES animated:YES];    
    for(UIView *subView in searchBar.subviews){        
        if([subView isKindOfClass:UIButton.class]){            
            [(UIButton*)subView setTitle:@"确定" forState:UIControlStateNormal];
;
        }        
    }
    return YES;
}

@end

